import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:live_music/models/moment_detail_model.dart';
import 'package:live_music/utils/cgq_utils.dart';
import 'package:video_player/video_player.dart';

class VideoPage extends StatefulWidget {
  VideoPage({Key key, this.momentId, this.videoItem}) : super(key: key);
  final int momentId;
  final Video videoItem;
  @override
  _VideoPageState createState() => _VideoPageState();
}

class _VideoPageState extends State<VideoPage>
    with SingleTickerProviderStateMixin {
  var _videoPlayerController;
  bool _isPlaying = false;
  String videoUrl;
//显示隐藏功能栏
  bool _isShow = true;
//显示倍速
  String _selectedValue = '倍速';
  List<String> items = ['1.0', '0.75', '0.5', '0.25'];
  bool showDuration = false;
//在initstate中初始化
  @override
  void initState() {
    _videoPlayerController = VideoPlayerController.network(widget.videoItem.url)
      ..initialize().then((_) {
        // 确保在初始化视频后显示第一帧，直至在按下播放按钮。
        setState(() {});
      });
    // _videoPlayerController.play();
    //执行监听，只要有内容就会刷新
    _videoPlayerController.addListener(() {
      setState(() {
        _isPlaying = _videoPlayerController.value.isPlaying;
      });
    });
  }

  void _playOrPause() {
    _isPlaying = !_isPlaying;
    if (_isPlaying) {
      _videoPlayerController.play();
    } else {
      _videoPlayerController.pause();
    }
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Container(
      color: Color(0XFF000000),
      child: Center(
        child: GestureDetector(
            // onTap: () {
            //   _playOrPause();
            // },
            onTapDown: (detail) {
              setState(() {
                _playOrPause();
              });
            },
            onTapUp: (detail) {},
            child: Container(
              width: double.infinity,
              height: double.infinity,
              color: Color(0XFF000000),
              child: Stack(
                alignment: Alignment.center,
                children: [
                  viDeoPlayer(),
                  kIsWeb
                      ? InkWell(
                          onTap: _playOrPause,
                          child: Center(
                            child: Container(),
                          ))
                      : Container(),
                  showDuration || !_isPlaying
                      ? Positioned(
                          left: 0,
                          bottom: 50,
                          right: 0,
                          child: Container(
                              padding:
                                  const EdgeInsets.only(right: 10, left: 10),
                              height: 20,
                              child: new Row(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: [
                                    Text(
                                      (_videoPlayerController.value.position
                                              .toString()
                                              .split('.')[0]
                                              .split(':')[1] +
                                          ":" +
                                          _videoPlayerController.value.position
                                              .toString()
                                              .split('.')[0]
                                              .split(':')[2]),
                                      style: TextStyle(
                                          fontSize: 14,
                                          color: Color(0xffefefef)),
                                    ),
                                    Text(
                                      " / ",
                                      style: TextStyle(
                                          fontSize: 14,
                                          color: Color(0xffefefef)),
                                    ),
                                    Text(
                                      (_videoPlayerController.value.duration
                                              .toString()
                                              .split('.')[0]
                                              .split(':')[1] +
                                          ":" +
                                          _videoPlayerController.value.duration
                                              .toString()
                                              .split('.')[0]
                                              .split(':')[2]),
                                      style: TextStyle(
                                          fontSize: 14,
                                          color: Color(0xffefefef)),
                                    ),
                                  ])))
                      : Container(),
                  Positioned(
                    bottom: 0,
                    left: 0,
                    right: 0,
                    child: Container(
                      padding: const EdgeInsets.only(right: 10, left: 10),
                      color: Color.fromRGBO(0, 0, 0, 0.5),
                      height: 20,
                      child: new Row(
                        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                        children: [
                          // //暂停按钮
                          // InkWell(
                          //   child: Icon(
                          //     Icons.pause,
                          //     size: 20,
                          //     color: Color(0xffefefef),
                          //   ),
                          //   onTap: () {
                          //     _videoPlayerController.pause();
                          //   },
                          // ),
                          //进度条
                          new Expanded(
                            child: SliderTheme(
                                data: SliderThemeData(
                                  trackHeight:
                                      showDuration || !_isPlaying ? 3 : 1,
                                  activeTrackColor: showDuration || !_isPlaying
                                      ? Colors.white
                                      : Colors.grey[700], // 激活的轨道颜色
                                  inactiveTrackColor:
                                      showDuration || !_isPlaying
                                          ? Colors.grey
                                          : Colors.grey[850],
                                  thumbColor: showDuration || !_isPlaying
                                      ? Colors.white
                                      : Colors.grey[800], // 滑块颜色
                                  thumbShape: RoundSliderThumbShape(
                                      //  滑块形状，可以自定义
                                      enabledThumbRadius:
                                          showDuration || !_isPlaying
                                              ? 5
                                              : 1 // 滑块大小
                                      ),
                                ),
                                child: Slider(
                                  // inactiveColor: Colors.grey,
                                  // activeColor: Color(0xffFFFFFF),
                                  max: _videoPlayerController
                                      .value.duration.inMilliseconds
                                      .truncateToDouble(),
                                  value: _videoPlayerController
                                      .value.position.inMilliseconds
                                      .truncateToDouble(),
                                  onChangeStart: (newRating) {
                                    setState(() {
                                      showDuration = true;
                                    });
                                  },
                                  onChangeEnd: (newRating) {
                                    setState(() {
                                      showDuration = false;
                                    });
                                  },
                                  onChanged: (newRating) {
                                    _videoPlayerController.seekTo(Duration(
                                        milliseconds: newRating.truncate()));
                                  },
                                )),
                            flex: 1,
                          ),
                          // //倍速下拉菜单
                          // DropdownButtonHideUnderline(
                          //   child: DropdownButton2(
                          //     hint: Text(
                          //       _selectedValue,
                          //       style: TextStyle(
                          //         fontSize: 18,
                          //         color: Color(0xffefefef),
                          //       ),
                          //     ),
                          //     items: items
                          //         .map((item) => DropdownMenuItem<String>(
                          //               value: item,
                          //               child: Text(
                          //                 '${item}x',
                          //                 style: const TextStyle(
                          //                   fontSize: 16,
                          //                 ),
                          //               ),
                          //             ))
                          //         .toList(),
                          //     // value: _selectedValue,
                          //     icon: Visibility(
                          //         visible: false,
                          //         child: Icon(Icons.arrow_downward)),
                          //     onChanged: (value) async {
                          //       double val = double.parse(value as String);
                          //       setState(() {
                          //         if (val == 1.0) {
                          //           _selectedValue = '倍速';
                          //         } else {
                          //           _selectedValue = '${value as String}x';
                          //         }
                          //       });
                          //     },
                          //     dropdownWidth: 100,
                          //     buttonWidth: 60,
                          //     iconSize: 36,
                          //     iconEnabledColor: Colors.white,
                          //     buttonPadding:
                          //         const EdgeInsets.only(left: 10),
                          //   ),
                          // ),
                        ],
                      ),
                    ),
                  )
                  // : new Container()
                  ,
                  _isPlaying
                      ? Container()
                      : InkWell(
                          child: Container(
                            width: 72,
                            height: 72,
                            child: Image.asset(
                              'assets/images/common/pause.webp',
                              fit: BoxFit.fill,
                            ),
                          ),
                          onTap: () {
                            _videoPlayerController.play();
                          },
                        ),
                ],
              ),
            )),
      ),
    ));
  }

  //******************建议视频播放控件封装成类或函数************************
  Widget viDeoPlayer() {
    return Container(
      width: double.infinity,
      height: double.infinity,
      color: Color(0xff000000),
      child: Center(
        //  _controller.value.initialized表示视频是否已加载并准备好播放，
        // 如果是true则返回AspectRatio（固定宽高比的组件,宽高比为视频本身的宽高比）
        // VideoPlayer为视频插放器，对像就是前面定义的_controller
        child: _videoPlayerController.value.isInitialized
            ? AspectRatio(
                aspectRatio: _videoPlayerController.value.aspectRatio,
                child: VideoPlayer(_videoPlayerController),
              )
            //如果视频没有加载好或者因网络原因加载不出来则返回Container 组件
            //一般用于放置过渡画面
            :Center(
                // child: Container(
                //   child: Text("视频加载中"),
                // ),
                  child: Container(
                  width: double.infinity,
                  child: CgqUtils.imageCache(
                  widget.videoItem.url+ "?x-oss-process=video/snapshot,t_0,f_jpg,w_0,h_0,m_fast,ar_auto",
                    fit: BoxFit.contain,
                  ),
                )
              ),
      ),
    );
  }

//销毁videoPlayerController
  @override
  void dispose() {
  
    _videoPlayerController.dispose();
    super.dispose();
  }
}
